package com.qingxin.park.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qingxin.park.entity.FarmPark;
import com.qingxin.park.entity.ParkBlock;
import com.qingxin.sys.dao.Querier;
import com.qingxin.sys.dao.Updater;
import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.mvc.PageParam;
import com.qingxin.sys.mvc.Pager;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.service.BaseService;
import com.qingxin.sys.support.SystemCfg;
import com.qingxin.sys.utils.BeanUtil;
import com.qingxin.sys.utils.StringUtils;
import com.qingxin.ui.bean.TreeNode;

/**
 * 园区地块
 * @author Administrator
 *
 */
@Service
public class ParkBlockService extends BaseService<ParkBlock, String> {
	
	@Autowired
	private FarmParkService farmParkService;
	
	@Autowired
	private SysUserBlockRelService sysUserBlockRelService;
	
	
	/**
	 * 获取菜单树数据
	 * @param parkid
	 * @param loginUser
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<TreeNode> getUITreeData(String parkid, boolean isParent, LoginUser loginUser){
		List<TreeNode> list = new ArrayList<TreeNode>();
		if(loginUser == null || StringUtils.isEmpty(parkid)){
			return list;
		}
		StringBuilder hql = new StringBuilder();
		hql.append("select new com.qingxin.park.entity.ParkBlock(b.blockid, b.blockName, b.farmPark.parkid)");
		hql.append(" from ParkBlock b where b.farmPark.parkid=? and b.isdel='0'");
		if(!SystemCfg.isDataAdminUser(loginUser)){
			hql.append(" and b.blockid in (select distinct v.parkBlock.blockid from SysUserBlockRel v where v.sysUser.userid='"+loginUser.getUserid()+"')");
		}
		hql.append(" order by b.blockName asc");
		
		List<ParkBlock> blocks = listByHql(hql.toString(), parkid);
		if(blocks != null){
			for(ParkBlock block : blocks){
				list.add(new TreeNode(block.getBlockid(), block.getBlockName(), SystemCfg.UI_DATATYPE_BLOCK, null, isParent));
			}
		}
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public List<TreeNode> getUITreeDataType(String parkid, String pdttype, boolean isParent, LoginUser loginUser){
		List<TreeNode> list = new ArrayList<TreeNode>();
		if(loginUser == null || StringUtils.isEmpty(parkid)){
			return list;
		}
		StringBuilder hql = new StringBuilder();
		hql.append("select new com.qingxin.park.entity.ParkBlock(b.blockid, b.blockName, b.farmPark.parkid)");
		hql.append(" from ParkBlock b where b.farmPark.parkid=? and b.isdel='0'");
		if(!SystemCfg.isDataAdminUser(loginUser)){
			hql.append(" and b.blockid in (select distinct v.parkBlock.blockid from SysUserBlockRel v where v.sysUser.userid='"+loginUser.getUserid()+"')");
		}
		
		String blockType = "4";
		if("1".equals(pdttype)){//种植
			blockType = "1";
		}else if ("2".equals(pdttype)) {//养殖
			blockType = "2";
		}else if ("3".equals(pdttype)) {//加工
			blockType = "3";
		}
		
		if(StringUtils.isNotEmpty(blockType)){
			hql.append(" and b.blockType='"+blockType.replace("'", "")+"' ");
		}
		hql.append(" order by b.blockName asc");
		
		List<ParkBlock> blocks = listByHql(hql.toString(), parkid);
		if(blocks != null){
			for(ParkBlock block : blocks){
				list.add(new TreeNode(block.getBlockid(), block.getBlockName(), SystemCfg.UI_DATATYPE_BLOCK, null, isParent));
			}
		}
		return list;
	}
	
	
	@SuppressWarnings("unchecked")
	public List<TreeNode> getUITreeDataParkAll(String parkid){
		List<TreeNode> list = new ArrayList<TreeNode>();
		StringBuilder hql = new StringBuilder();
		hql.append("select new com.qingxin.park.entity.ParkBlock(b.blockid, b.blockName, b.farmPark.parkid)");
		hql.append(" from ParkBlock b where b.farmPark.parkid=? and b.isdel='0'");
		hql.append(" order by b.blockName asc");
		List<ParkBlock> blocks = listByHql(hql.toString(), parkid);
		if(blocks != null){
			for(ParkBlock block : blocks){
				list.add(new TreeNode(block.getBlockid(), block.getBlockName(), SystemCfg.UI_DATATYPE_BLOCK, null, false));
			}
		}
		return list;
	}
	
	
	
	/**
	 * 获取列表数据
	 * @param parkid
	 * @param blockName
	 * @param isuse
	 * @param pageParam
	 * @param loginUser
	 * @return
	 */
	public Pager list(String parkid, String blockName, String blockType, String isuse, PageParam pageParam, LoginUser loginUser){
		Querier querier = Querier.create("select new com.qingxin.park.entity.ParkBlock(" +
				"p.blockid, p.blockCode, p.blockName, p.blockType, p.isuse, p.area)" +
				" from ParkBlock p where p.farmPark.parkid=:parkid and p.isdel='0'");
		querier.setParam("parkid", parkid);
		if(StringUtils.isNotEmpty(blockType)){
			querier.append(" and p.blockType=:blockType ");
			querier.setParam("blockType", blockType);
		}
		if(!SystemCfg.isDataAdminUser(loginUser)){
			querier.append(" and p.blockid in (select distinct v.parkBlock.blockid from SysUserBlockRel v where v.sysUser.userid=:userid)");
			querier.setParam("userid", loginUser.getUserid());
		}
		if(StringUtils.isNotEmpty(blockName)){
			blockName = blockName.replace("'", "");
			querier.append(" and (p.blockName like :blockName or p.blockCode like :blockCode) ");
			querier.setParam("blockName", "%"+blockName+"%");
			querier.setParam("blockCode", "%"+blockName+"%");
		}
		
		querier.append(pageParam.getOrderby(" order by p.blockName asc"));
		
		Pager pager = pageByQuerier(querier, pageParam);
		return pager;
		
	}
	
	
	/**
	 * 添加地块信息
	 * @param block
	 * @param parkid
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError add(ParkBlock block, String parkid, LoginUser loginUser, HttpServletRequest request){
		FarmPark park = farmParkService.get(parkid);
		if(park == null){
			return new SysError("参数错误");
		}
		if(isNameDuplicate(block.getBlockName(), null, parkid)){
			return new SysError("该名称已存在");
		}
		if(isCodeDuplicate(block.getBlockCode(), null, parkid)){
			return new SysError("该编号已存在");
		}

		block.setFarmPark(new FarmPark(parkid));

		Date now = new Date();
		block.setCreateTime(now);
		block.setUpdateTime(now);
		block.setCreateBy(loginUser.getLogin_name());
		block.setUpdateBy(loginUser.getLogin_name());
		
		block.setIsdel("0");
		
		this.save(block);
		
		//添加用户园区关联关系
		if(!SystemCfg.isDataAdminUser(loginUser)){
			sysUserBlockRelService.addUserBlockRel(loginUser.getUserid(), block.getBlockid(), loginUser);
		}
		
		return null;
		
	}
	
	
	/**
	 * 修改地块信息
	 * @param block
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError update(ParkBlock block, LoginUser loginUser, HttpServletRequest request){
		ParkBlock old = getSafeEntity(block.getBlockid());
		if(old == null){
			return new SysError("参数错误");
		}
		if(isNameDuplicate(block.getBlockName(), block.getBlockid(), old.getFarmPark().getParkid())){
			return new SysError("该名称已存在");
		}
		if(isCodeDuplicate(block.getBlockCode(), block.getBlockid(), old.getFarmPark().getParkid())){
			return new SysError("该编号已存在");
		}
		
		
		String fields = "blockCode,blockName,isuse,remark,area";
		BeanUtil.setTargetFields(old, block, fields, true);
		
		old.setUpdateBy(loginUser.getLogin_name());
		old.setUpdateTime(new Date());
		
		Updater<ParkBlock> updater = new Updater<>(old, fields+",updateBy,updateTime");
		this.update(updater);
		
		return null;
		
	}
	
	
	/**
	 * 删除地块信息
	 * @param blockids
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public Object delete(String[] blockids, LoginUser loginUser, HttpServletRequest request){
		for(String blockid : blockids){
			ParkBlock block = get(blockid);
			if(block==null){
				continue;
			}
			
			Object obj = getByHql("select plantid from ParkBlockPlant where parkBlock.blockid=?", blockid);
			if(obj!=null){
				return new SysError("地块 “"+block.getBlockName()+"” 下有种植信息，不能删除.");
			}
			
			this.delete(block);
		}
		return null;
	}
	
	
	/**
	 * 判断指定名称是否被使用
	 * @param blockName
	 * @param blockid
	 * @param parkid
	 * @return
	 */
	public boolean isNameDuplicate(String blockName, String blockid, String parkid){
		if(StringUtils.isEmpty(blockid)){
			Object obj = getByHql("select blockid from ParkBlock where farmPark.parkid=? and blockName=?", parkid, blockName);
			return obj!=null;
		}else {
			Object obj = getByHql("select blockid from ParkBlock where farmPark.parkid=? and blockName=? and blockid<>?", parkid, blockName, blockid);
			return obj!=null;
		}
	}
	
	/**
	 * 判断指定CODE是否被使用
	 * @param blockCode
	 * @param blockid
	 * @param parkid
	 * @return
	 */
	public boolean isCodeDuplicate(String blockCode, String blockid, String parkid){
		if(StringUtils.isEmpty(blockid)){
			Object obj = getByHql("select blockid from ParkBlock where farmPark.parkid=? and blockCode=?", parkid, blockCode);
			return obj!=null;
		}else {
			Object obj = getByHql("select blockid from ParkBlock where farmPark.parkid=? and blockCode=? and blockid<>?", parkid, blockCode, blockid);
			return obj!=null;
		}
	}
	
	
}
